package com.yimi.yinhepda.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.yaohua.bluetoothlib.BluetoothManager;
import com.yaohua.bluetoothlib.method.WeighBean;
import com.yimi.yinhepda.BuildConfig;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.BillRouteTableDao;
import com.yimi.yinhepda.db.dao.JieLiuJianTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.helper.DbHelperUC;
import com.yimi.yinhepda.db.table.BillRouteTable;
import com.yimi.yinhepda.db.table.JieLiuJianTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.yimi.yinhepda.downLoadBaseData.DownLoadBaseData;
import com.yimi.yinhepda.downLoadBaseData.DownLoadFile;
import com.yimi.yinhepda.downLoadBaseData.DownLoadForOffLineData;
import com.yimi.yinhepda.entity.request.QueryUcRemindRequest;
import com.yimi.yinhepda.entity.response.QueryJieLiuJianResponse;
import com.yimi.yinhepda.entity.response.QueryUcRouteDbResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.GzipUtil;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.yimi.yinhepda.views.check_balance.CheckBalanceActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙秤连接服务
 *
 * @author 000432
 * @date 2018/1/11 0011
 */

public class CommonService extends Service implements BluetoothManager.onBluetoothListener {

    /**
     * 蓝牙管理
     */
    protected BluetoothManager bluetoothManager;
    /**
     * 蓝牙条码
     */
    private String blueToothNum;
    private int connCount = 0;
    private SharedPreferUtil sharedPreferUtil;
    /**
     * 截留件处理
     */
    private Handler jieLiuHandler = new Handler();
    /**
     * 间隔300秒(五分钟)
     */
    private long loadTime = 1000 * 120;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //两分钟一次拉取截留件单号
            queryJieLiuJian();
            //两分钟一次下拉路由db文件
            getUcRouteDB();
            // 间隔120秒(两分钟)
            jieLiuHandler.postDelayed(this, loadTime);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        bluetoothManager = new BluetoothManager(this);
        bluetoothManager.setOnBluetoothListener(this);
        sharedPreferUtil = SharedPreferUtil.getInstance();

        //判断是否需要下载数据
        if (!sharedPreferUtil.getOfflineMode()) {
            //下载基础数据
            if (!sharedPreferUtil.getServerIpHaveChanged()) {
                if (BuildConfig.DEBUG) {
//                    new DownLoadBaseData(this, false).downloadBaseData();
                } else {
                    new DownLoadBaseData(this, false).downloadBaseData();
                }
            }
            //下载月台号和装卸组数据、部门所有用户
            new DownLoadForOffLineData(getApplicationContext()).startDownLoadPlatformNoData();
        }

        //定时下拉NOS的所有截留和拦截单号
        jieLiuHandler.postDelayed(runnable, 1000);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bluetoothManager != null) {
            bluetoothManager.onStop();
        }
        if (jieLiuHandler != null) {
            jieLiuHandler.removeCallbacks(runnable);
        }
    }

    class MyBinder extends Binder implements IService {

        @Override
        public void connectBlueToothDevice(String result) {
            connCount = 0;
            blueToothNum = result;
            bluetoothManager.connectDevice(result);
        }

        @Override
        public WeighBean getWeight() {
            WeighBean weigh = bluetoothManager.getWeigh();
            return weigh;
        }

        @Override
        public void openBluetooth() {
            //打开蓝牙
            bluetoothManager.openBluetooth();
        }
    }

    public interface IService extends Serializable {
        void connectBlueToothDevice(String result);

        WeighBean getWeight();

        void openBluetooth();
    }

    /**
     * 重启蓝牙
     */
    private void restartBlueTooth() {
        if (bluetoothManager != null) {
            bluetoothManager.onStop();
            bluetoothManager = null;
        }
        bluetoothManager = new BluetoothManager(this);
        bluetoothManager.setOnBluetoothListener(this);
        bluetoothManager.openBluetooth();
        if (connCount <= 3 && blueToothNum != null) {
            Log.e("蓝牙连接次数----->", connCount + "");
            connCount++;
            stateBounding();
            bluetoothManager.connectDevice(blueToothNum);
        }
    }

    /***
     * 发送请求至复秤检查界面
     */
    private void sendHandlerFunction(int color, String connResult, int visibility) {
        if (CheckBalanceActivity.handler != null) {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putInt("color", color);
            bundle.putString("connResult", connResult);
            bundle.putInt("visibility", visibility);
            msg.setData(bundle);
            msg.what = CheckBalanceActivity.HANDLER_ONE;
            CheckBalanceActivity.handler.sendMessage(msg);
        }
    }

    @Override
    public void openBlueToothFirst() {
        //先开启蓝牙
        bluetoothManager.openBluetooth();
        sendHandlerFunction(Color.BLACK, "正在开启蓝牙", View.GONE);
    }

    @Override
    public void stateHasConnecte() {
        //蓝牙已连接
        if (CheckBalanceActivity.handler != null) {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            msg.setData(bundle);
            msg.what = CheckBalanceActivity.HANDLER_TWO;
            CheckBalanceActivity.handler.sendMessage(msg);
        }
    }

    @Override
    public void stateConnected() {
        connCount = 0;
        //蓝牙连接成功
        sendHandlerFunction(this.getResources().getColor(R.color.colore1d9717), "蓝牙连接成功！", View.VISIBLE);
        SharedPreferUtil.getInstance().setValue(Common.BLUE_TOOTH_NUM, blueToothNum);
        /**
         * 蓝牙读流是阻塞式的，数据不畅通的话，
         * 会阻塞在 【count = inputStream.read(buffer, 0, length);】
         * 先去确保数据畅通
         */
    }

    @Override
    public void stateDisConnected() {
        //蓝牙未连接
        sendHandlerFunction(Color.RED, "蓝牙未连接，请扫描重试！", View.VISIBLE);
        //重启蓝牙
        restartBlueTooth();
    }

    @Override
    public void stateConnecting() {
        sendHandlerFunction(Color.BLACK, "蓝牙连接中...", View.VISIBLE);
    }

    @Override
    public void stateBoundNone() {
        sendHandlerFunction(Color.RED, "蓝牙配对失败！请扫描重试", View.VISIBLE);
        //重启蓝牙
        restartBlueTooth();
    }

    @Override
    public void stateBounding() {
        sendHandlerFunction(Color.BLACK, "蓝牙配对中...", View.VISIBLE);
    }

    @Override
    public void stateBounded() {
        sendHandlerFunction(Color.BLACK, "蓝牙配对成功！", View.VISIBLE);
    }

    @Override
    public void stateBoundRequest() {
        sendHandlerFunction(Color.BLACK, "蓝牙配对请求，请输入PIN码！", View.VISIBLE);
    }

    /**
     * 查询截留件，将数据保存至本地7天
     */
    private void queryJieLiuJian() {
        QueryUcRemindRequest request = new QueryUcRemindRequest();
        request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        request.setSyncStartTime(sharedPreferUtil.getValue(Common.JIE_LIU_JIAN_SYNC_TIME));
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryJieLiuJianResponse.class)
                .setUrl(Constants.URL_CHECK_INTERCEPT_PART)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryJieLiuJianResponse response = (QueryJieLiuJianResponse) obj;
                        if (response != null && response.getData() != null) {
                            String syncTime = response.getData().getSyncStartTime();
                            LogUtil.e("syncTime----->" + syncTime);
                            sharedPreferUtil.setValue(Common.JIE_LIU_JIAN_SYNC_TIME, syncTime);
                            String interceStr = GzipUtil.uncompress(response.getData().getCompressInterceptorStr());
                            LogUtil.e("InterceptorStr----->" + interceStr);
                            if (interceStr != null) {
                                List<JieLiuJianTable> jianTableList = new ArrayList<>();
                                try {
                                    //截留件json解析
                                    JSONArray array = new JSONArray(interceStr);
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject object = array.getJSONObject(i);
                                        JieLiuJianTable jieLiuJianTable = new JieLiuJianTable();
                                        jieLiuJianTable.setBillCode(object.getString("billCode"));
                                        jieLiuJianTable.setNosPdaMark(object.getString("nosPdaMark"));
                                        jieLiuJianTable.setOperateStatus(object.getString("operateStatus"));
                                        jianTableList.add(jieLiuJianTable);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                new JieLiuJianTableDao().createOrUpdate(jianTableList);
                            }
                        }
                    }
                });
    }

    /**
     * 获取快递路由db文件
     */
    private void getUcRouteDB() {
        //判断快递路由表是否存在，不存在删除数据库，重新下载
        File file = new File(DbHelperUC.DB_PATH, DbHelperUC.DB_NAME);
        boolean isExitTable = new BillRouteTableDao().tableIsExist("t_utp_app_bill_route");
        if (!isExitTable && file.exists()) {
            file.delete();
        }
        //判断当前网点是否有对应的快递网点，没有无需查询
        UCDeptTable ucDeptTable = new UCDeptTableDao().findDataByDeptCode(sharedPreferUtil.getDeptCode());
        if (ucDeptTable != null) {
            //查询本地快递路由db文件是否存在，不存在则下载路由db文件，存在则增量更新
            if (!file.exists()) {
                QueryUcRemindRequest request = new QueryUcRemindRequest();
                request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
                request.setSyncStartTime(sharedPreferUtil.getValue(Common.UC_ROUTE_DB_SYNC_TIME));
//                request.setSrcDeptCode("029W");
//                request.setSyncStartTime("1575072002000");
                new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                        .setResponsClazz(QueryUcRouteDbResponse.class)
                        .setUrl(Constants.URL_GET_UC_ROUTE_DB)
                        .setRequestObject(request)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                LogUtil.e(msg);
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                QueryUcRouteDbResponse response = (QueryUcRouteDbResponse) obj;
                                if (response.getData() != null) {
                                    QueryUcRouteDbResponse.DataBean dataBean = response.getData();
                                    if (dataBean != null) {
                                        new DownLoadFile(getApplicationContext()).downloadUcRouteDbFile(dataBean);
                                    }
                                }
                            }
                        });
            } else {
                //清除快递路由7天前的数据
                DbHelperUC.deleteData();
                //快递路由db文件存在，则调用增量接口
                QueryUcRemindRequest request = new QueryUcRemindRequest();
                request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
                request.setSyncStartTime(sharedPreferUtil.getValue(Common.UC_ROUTE_DB_SYNC_TIME));
//                request.setSrcDeptCode("029W");
//                request.setSyncStartTime("1575072002000");
                new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                        .setResponsClazz(QueryUcRouteDbResponse.class)
                        .setUrl(Constants.URL_QUERY_UC_ROUTE)
                        .setRequestObject(request)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                LogUtil.e(msg);
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                QueryUcRouteDbResponse response = (QueryUcRouteDbResponse) obj;
                                if (response.getData() != null) {
                                    QueryUcRouteDbResponse.DataBean dataBean = response.getData();
                                    if (dataBean != null && dataBean.getLisData() != null) {
                                        Gson gson = new Gson();
                                        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(gson.toJson(response.getData()));
                                        String listData = GzipUtil.uncompressToString(jsonObject.getBytes("lisData"), GzipUtil.GZIP_ENCODE_UTF_8);
                                        if (listData != null) {
                                            LogUtil.e(listData);
                                            try {
                                                List<BillRouteTable> billRouteTableList = new ArrayList<>();
                                                JSONArray array = new JSONArray(listData);
                                                for (int i = 0; i < array.length(); i++) {
                                                    JSONObject object = array.getJSONObject(i);
                                                    BillRouteTable billRouteTable = new BillRouteTable();
                                                    billRouteTable.setBillCode(object.getString("billCode"));
                                                    billRouteTable.setEndStationCode(object.getString("endStationCode"));
                                                    billRouteTable.setEndStationName(object.getString("endStationName"));
                                                    billRouteTable.setFinalStationName(object.getString("finalStationName"));
                                                    billRouteTable.setUpdateTime(String.format("%s", object.getLong("updateTime")));
                                                    billRouteTableList.add(billRouteTable);
                                                }
                                                int i = new BillRouteTableDao().insert(billRouteTableList);
                                                if (i != -1 && dataBean.getIncrementTime() != null) {
                                                    sharedPreferUtil.setValue(Common.UC_ROUTE_DB_SYNC_TIME, dataBean.getIncrementTime());
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            } catch (SQLException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }
                        });
            }
        }
    }
}
